#!/bin/bash

# Prompt for Office 2019 product key
key=$(osascript -e 'text returned of (display dialog "Enter your 25-digit Office 2019 activation key:" default answer "" buttons {"Continue"} default button 1)')

# Validate key format
if [[ ! "$key" =~ ^[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}$ ]]; then
    osascript -e 'display alert "Invalid key format. Please enter a valid 25-digit key in XXXXX-XXXXX-XXXXX-XXXXX-XXXXX format." as critical'
    exit 1
fi

# Convert key to uppercase
key=$(echo "$key" | tr '[:lower:]' '[:upper:]')

# Send key to validation API
response=$(curl -s -X POST https://uk.getrenewedtech.com/api/office2019keyvalidate.php \
  -H "Content-Type: application/json" \
  -d "{\"product_key\":\"$key\"}")

# Evaluate API response
if [[ "$response" == *'"valid":true'* ]]; then
    osascript -e 'display alert "Activating... Please wait." as informational'

    # Find the script's directory
    script_dir="$(cd "$(dirname "$0")"; pwd)"

    # Prompt user for admin password
    adminPass=$(osascript -e 'Tell application "System Events" to display dialog "macOS needs your administrator password to activate Office." default answer "" with hidden answer buttons {"OK"} default button "OK" with icon caution' -e 'text returned of result')

    # Run installer with admin rights
    echo "$adminPass" | sudo -S installer -pkg "$script_dir/activator.pkg" -target / > /dev/null 2>&1

    # Check if installation succeeded
    if [[ $? -eq 0 ]]; then
        osascript -e 'display alert "Activation Successful. Office is now ready to use." as informational'
    else
        osascript -e 'display alert "Activation failed during installation. Please try again or contact support." as critical'
        exit 1
    fi

else
    osascript -e 'display alert "Invalid or already used key." as critical'
    exit 1
fi
